package com.hup.utils.swing.customView.viewTable2;

import com.hup.utils.commons.hardware.SystemUtil;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 表头菜单,可重写方法,实现自定义菜单
 */
public class VHeaderMenu<R> implements ActionListener {
    public static final String CMD_RESET_SORT = "重置排序";
    public static final String CMD_RESET_WIDTH = "重置列宽";
    public static final String CMD_COPY_HEAD = "复制表头";

    private final ViewTable<R> table;
    private final JPopupMenu headerMenu;

    public VHeaderMenu(ViewTable<R> table) {
        this.table = table;
        headerMenu = new JPopupMenu();
        for (JMenuItem item : buildMenu()) {
            if (item == null) {
                headerMenu.addSeparator();
                continue;
            }
            headerMenu.add(item);
            item.addActionListener(this);
        }
    }

    public void mouseClicked(ViewTable<R> table, MouseEvent e) {
        headerMenu.show(e.getComponent(), e.getX(), e.getY());
    }

    //===可重写的方法
    public List<JMenuItem> buildMenu() {
        List<JMenuItem> res = new ArrayList<>();
        res.add(new JMenuItem(CMD_RESET_SORT));
        res.add(new JMenuItem(CMD_RESET_WIDTH));
        res.add(new JMenuItem(CMD_COPY_HEAD));
        return res;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
            case CMD_RESET_SORT:
                table.getRowSorter().setSortKeys(null);
                return;
            case CMD_RESET_WIDTH:
                table.resetColumnWidth();
                return;
            case CMD_COPY_HEAD:
                String str = table.getColumns().stream()
                        .filter(VColumnInfo::isVisible)
                        .map(VColumnInfo::getName)
                        .collect(Collectors.joining(","));
                SystemUtil.saveToClipboard(str);
        }
    }
}
